package com.common.utils;

import com.alibaba.excel.EasyExcel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@Component
public class ExportUtil<T> {

    @Resource
    HttpServletResponse response;
    //导出
    /**
     * 导出Excel表格
     *
     * @param name 文件名
     * @param list 要导出的数据列表
     * @param tClass 数据类的Class对象，用于确定列表中数据的类型
     * @throws IOException 如果文件写入过程中发生I/O错误
     */
    public void expExcel(String name, List<T> list, Class<T> tClass) throws IOException {
        try {
            //设置响应头信息
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //编码
            response.setCharacterEncoding("utf-8");
            //文件名称
            String filename = URLEncoder.encode(name, "UTF-8").replaceAll("\\+", "%20");
            //设置头信息
            response.setHeader("content-disposition", "attachment;filename*=utf-8''" + filename + ".xlsx");
            //使用EasyExcel写入信息
            EasyExcel.write(response.getOutputStream(), tClass).sheet(name).doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭流
            response.getOutputStream().close();
        }
    }

}